Ext.define('appmod.view.knowledge.content.upload.MultiFile', {
    extend: 'Ext.grid.Panel',
    alias: ['widget.knowledge.content.upload.multifile', 'widget.knowledge-content-upload-multifile'],
    region: 'center',
    bodyPadding: 10,
    requires: [
	'vsg.framework.button.SWFUploadButton',
	 'appmod.model.FileModel'],
    
    constructor: function(config){
		    
        this.callParent(arguments);
    },
    
    initComponent: function(){
        var me = this;
		
        Ext.applyIf(me, {
            columns: [{
                xtype: 'gridcolumn',
                dataIndex: 'fileName',
                header: '文件名称',
                flex: 1,
				sortable: false,
                minWidth: '250'
            }, {
                xtype: 'gridcolumn',
                dataIndex: 'uploadStatus',
                header: '状态',
				sortable: false,
                minWidth: '60',
                renderer: function(value){
                    if (value == SWFUpload.FILE_STATUS.QUEUED) {
                        return '未上传';
                    }
                    else 
                        if (value == SWFUpload.FILE_STATUS.IN_PROGRESS) {
                            return '正在上传';
                        }
                        else 
                            if (value == SWFUpload.FILE_STATUS.ERROR) {
                                return '上传错误';
                            }
                            else 
                                if (value == SWFUpload.FILE_STATUS.COMPLETE) {
                                    return '上传成功';
                                }
                                else 
                                    if (value == SWFUpload.FILE_STATUS.CANCELLED) {
                                        return '上传取消';
                                    }
                    
                }
            }, {
                xtype: 'actioncolumn',
                dataIndex: 'fileAction',
				sortable: false,
                header: '操作',
                minWidth: '60',
				items:[{
                        getClass: function(v, meta, rec){
							return 'x-action-del';
                        },
                        handler: me.deleteFileItem
                    }
					]
            }],
            viewConfig: {},
            dockedItems: [{
                xtype: 'toolbar',
                dock: 'top',
                items: [{
                    xtype: 'swfupload.button',
                    text: '上传文件',
					base_setting:me.base_setting,
                    action: 'uploadFile'
                }]
            }]
        });
        
        me.callParent(arguments);
        
        // --- add event for button ---
        var swfBtn = me.down('swfupload-button');
        swfBtn.addListener('fileQueued', me.showFileItems, me);
		swfBtn.addListener('uploadProgress', me.updateUploadProcess, me);
		swfBtn.addListener('uploadSuccess', me.uploadSuccess, me);
		swfBtn.addListener('uploadError', me.uploadError, me);
		swfBtn.addListener('uploadComplete', me.uploadComplete, me);
		swfBtn.addListener('fileDialogComplete', me.fileDialogComplete, me);

        // --- flash store ---
		me.synchronize();
        
    },
    
    showFileItems: function(button, file){
        // --- get store ---
        var store = this.getStore();
        
        var r = Ext.create('appmod.model.FileModel', {
            id: file['id'],
            fileName: file['name'],
            uploadStatus: file['filestatus']
        });
		store.add(r);


    },
	
	deleteFileItem:function(grid, rowIndex, colIndex) {
		var me = this;
		
		var gridStore = grid.getStore();
		var rec = gridStore.getAt(rowIndex);
        var resId = rec.getId();
		
		// --- delete query ---
		var parentGrid = me.up('knowledge-content-upload-multifile');
		var swfUploadBtn = parentGrid.down('swfupload-button');
		var swfUploadComp = swfUploadBtn.getSWFUpload();

		if ( rec.getId() ) {
			swfUploadComp.cancelUpload(  rec.getId() );
			// --- remove current file ---
			gridStore.remove(rec);
		}
	},


	
	updateUploadProcess:function(button, eOpts) {
		var me = this;
		var file = eOpts['file'];
		var completeBytes = eOpts['completeBytes'];
		var totalByte = eOpts['totalByte'];

		// --- get upload files ---
		var fileId =  file['id'];
	
		var store = me.getStore();
		var record = store.getById(fileId);

		if (record) {
			var status = record.get('uploadStatus');
			// --- update resource ---
			if (status != file['filestatus'])  {
				record.set('uploadStatus' , file['filestatus']);
				record.commit();
			} 
		}
		// --- update resource ---
		//record.endEdit();

		
		

		
	},
	
	uploadSuccess:function(button, eOpts) {
		var file = eOpts['file'];
		var serverData = eOpts['serverData'];
		var receivedResponse = eOpts['receivedResponse'];
	

		
	},
	
	uploadError:function(button, eOpts) {
		var me = this;
		var file = eOpts['file'];
		var errorCode = eOpts['errorCode'];
		var message = eOpts['message'];

		var fileId =  file['id'];
		
		console.log('upload error : ' + errorCode + " , " + message);
		
	
		var store = me.getStore();
		var record = store.getById(fileId);
		if (record) {
			var status = record.get('uploadStatus');
			// --- update resource ---
			if (status != file['filestatus'])  {
				record.set('uploadStatus' , file['filestatus']);
				record.commit();
			} 
		}

		
	},
	
	uploadComplete:function(button, eOpts) {
		var me = this;
		
		var file = eOpts['file'];
		
		var fileId =  file['id'];
	
		var store = me.getStore();
		var record = store.getById(fileId);
		if (record) {
			var status = record.get('uploadStatus');
			// --- update resource ---
			if (status != file['filestatus'])  {
				record.set('uploadStatus' , file['filestatus']);
				record.commit();
			} 
		}
		
		
		// --- check all queued files whether completed ---
		var index = file['index'];
		if (index == store.getCount() - 1 ) {
			// --- fire all file upload complete ---
			me.fireEvent('uploadSuccess' , {
				
			});
		}

	},
	
	/**
	 * fire event when the select window closed
	 * @param {Object} button
	 * @param {Object} eOpts
	 */
	fileDialogComplete:function(button, eOpts) {
		var selectedFileNum = eOpts['selectedFileNum'];
		var queuedFileNum = eOpts['queuedFileNum'];
		var totalQueuedFileNum = eOpts['totalQueuedFileNum'];

	},
	
	/**
	 * synchroniza grid store from object 
	 */
	synchronize:function() {
		var me = this;

        var swfBtn = me.down('swfupload-button');
		var swfUploadComp = swfBtn.getSWFUpload();
		
		
	
		
	}
	
	
});
